package com.xierong.remoteplayerlauncher;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.source.ConcatenatingMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.xierong.remoteplayerlauncher.model.PlayListItem;
import com.xierong.remoteplayerlauncher.recevier.UDPListenerRecevier;
import com.xierong.remoteplayerlauncher.service.UDPListenerService;
import com.xierong.remoteplayerlauncher.utils.PlayerManager;
import com.xierong.remoteplayerlauncher.recevier.ExternalStorageReceiver;
import com.xierong.remoteplayerlauncher.recevier.ExternalStorageReceiverHelper;
import com.xierong.remoteplayerlauncher.recevier.ExternalStorageReceiverHelper.ExternalStorageCommand;

import java.io.File;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class VideoActivity extends AppCompatActivity implements UDPListenerRecevier.UDPCommand, ExternalStorageCommand {
    public static final String MEDIA_PLAYING_TYPE_VIDEO = "playingTypeVideo";
    public static final String MEDIA_PLAYING_TYPE_IMAGE = "playingTypeImage";
    private ExternalStorageReceiverHelper externalStorageReceiverHelper = null;
    private PlayerView playerView;
    private ExoPlayer player;
    private ImageView imageView;
    private boolean playWhenReady = true;
    private int currentWindow;
    private long playbackPosition;
    private long exitTime = 0;
    private Timer timer = null;
    private boolean isTimerRunning = false;
    private TimerTask timerTask = null;
    private String currentPlayingMediaType = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_video);
        playerView = findViewById(R.id.video_view);
        imageView = findViewById(R.id.image_view);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UDPListenerService.UDP_RECEIVER);
        UDPListenerRecevier udpListenerRecevier = new UDPListenerRecevier();
        registerReceiver(udpListenerRecevier, intentFilter);
        udpListenerRecevier.setUdpListener(this);
        Intent udpIntent = new Intent(getApplicationContext(),UDPListenerService.class);
        startService(udpIntent);
        listenExternalStorageEvents();
    }

    private void listenExternalStorageEvents() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ExternalStorageReceiver.EXTERNAL_STORAGE_CONFIG_PATH);
        intentFilter.addAction(ExternalStorageReceiver.EXTERNAL_STORAGE_NO_CONFIG);
        intentFilter.addAction(ExternalStorageReceiver.EXTERNAL_STORAGE_UNMOUNTED);
        externalStorageReceiverHelper = new ExternalStorageReceiverHelper();
        externalStorageReceiverHelper.setCommand(this);
        registerReceiver(externalStorageReceiverHelper, intentFilter);
    }

    private void initializePlayer() {
        if (player == null) {
            // let the factory create a player instance with default components
            player = ExoPlayerFactory.newSimpleInstance(this,
                    new DefaultTrackSelector(), new DefaultLoadControl());
            playerView.setPlayer(player);
            playerView.setControllerAutoShow(false);
            player.setPlayWhenReady(playWhenReady);
            player.seekTo(currentWindow, playbackPosition);
            player.addListener(eventListener);

        }
    }

    public void startPlay() {
        PlayListItem current = PlayerManager.getInstance().getCurrentPlaying();
        if(current.getType().equals("image")) {
            playImage(current.getPath(), current.getDuration());
        } else if (current.getType().equals("video")) {
            playVideo(current.getPath());
        }
    }

    public void playVideo(String path) {
        imageView.setImageURI(null);
        imageView.setVisibility(View.INVISIBLE);
        playerView.setVisibility(View.VISIBLE);
        if(player == null) {
            initializePlayer();
        }
        String playerInfo = Util.getUserAgent(getApplicationContext(), "RemotePlayerLauncher");
        DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(getApplicationContext(), playerInfo);
        MediaSource mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.fromFile(new File(path)));
        player.prepare(mediaSource);
        player.setPlayWhenReady(true);
        this.currentPlayingMediaType = VideoActivity.MEDIA_PLAYING_TYPE_VIDEO;
    }
    private ExoPlayer.EventListener eventListener = new ExoPlayer.EventListener(){
        @Override
        public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
            switch (playbackState){
                case ExoPlayer.STATE_ENDED:
                    UDP_Next();
                    break;
            }
        }
    };
    public void playImage(String path, String duration) {
        releasePlayer();
        imageView.setVisibility(View.VISIBLE);
        playerView.setVisibility(View.INVISIBLE);
        imageView.setImageURI(Uri.fromFile(new File(path)));
        try {
            long ms = Integer.parseInt(duration);
            if(ms<=0) {
                UDP_Next();
                return;
            }
            timer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(() -> {
                        UDP_Next();
                    });
                }
            };
            timer.schedule(timerTask,ms);
            isTimerRunning = true;
        } catch(NumberFormatException e) {
            e.printStackTrace();
            UDP_Next();
        }
        this.currentPlayingMediaType = VideoActivity.MEDIA_PLAYING_TYPE_IMAGE;
    }

    private MediaSource buildPlayList(ArrayList<PlayListItem> list) {
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "RemotePlayerLauncher"));
        MediaSource[] mediaSources = new MediaSource[list.size()];
        for(int i = 0;i<list.size();i++){
            Uri uri = Uri.parse(list.get(i).getPath());
            mediaSources[i] = new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
        }
        MediaSource mediaSource = mediaSources.length == 1 ? mediaSources[0] : new ConcatenatingMediaSource(mediaSources);
        return mediaSource;
    }

    private void releasePlayer() {
        if (player != null) {
            playbackPosition = player.getCurrentPosition();
            currentWindow = player.getCurrentWindowIndex();
            playWhenReady = player.getPlayWhenReady();
            player.release();
            player = null;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        startPlay();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(PlayerManager.TAG,"播放器视图：STOP");
        if (Util.SDK_INT >= 23) {
            releasePlayer();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (Util.SDK_INT >= 23) {
            releasePlayer();
        }
    }

    @Override
    protected void onDestroy() {
        Log.d(PlayerManager.TAG, "------------------------------------播放器视图正在销毁");
        if (Util.SDK_INT >= 23) {
            releasePlayer();
        }
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                onDestroy();
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    public void UDP_Play() {
        Log.d(PlayerManager.TAG, "UDP消息：PLAY");
        if (this.player != null && this.currentPlayingMediaType == VideoActivity.MEDIA_PLAYING_TYPE_VIDEO) {
            player.setPlayWhenReady(true);
        } else if (this.timer != null && this.currentPlayingMediaType == VideoActivity.MEDIA_PLAYING_TYPE_IMAGE) {
            if (!isTimerRunning) {
                String duration = PlayerManager.getInstance().getCurrentPlaying().getDuration();
                String path = PlayerManager.getInstance().getCurrentPlaying().getPath();
                playImage(path, duration);
            }
        }
    }
    @Override
    public void UDP_Pause() {
        Log.d(PlayerManager.TAG, "UDP消息：PAUSE");
        if (this.player!=null && this.currentPlayingMediaType == VideoActivity.MEDIA_PLAYING_TYPE_VIDEO) {
            player.setPlayWhenReady(false);
        } else if (this.timer!=null && this.currentPlayingMediaType == VideoActivity.MEDIA_PLAYING_TYPE_IMAGE) {
            if (isTimerRunning) {
                timer.cancel();
                isTimerRunning = false;
            }
        }
    }
    @Override
    public void UDP_Restart() {
        if (timer!=null) {
            timer.cancel();
            isTimerRunning = false;
        }
        PlayerManager.getInstance().restart();
        startPlay();
        Log.d(PlayerManager.TAG, "UDP消息：RESTART");
    }
    @Override
    public void UDP_Loop() {
        PlayerManager.getInstance().setLoop();
        Log.d(PlayerManager.TAG, "UDP消息：LOOP");
    }
    @Override
    public void UDP_Volup() {
        Log.d(PlayerManager.TAG, "UDP消息：VOL_UP");
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
    }
    @Override
    public void UDP_Voldown() {
        Log.d(PlayerManager.TAG, "UDP消息：VOL_DOWN");
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
    }
    @Override
    public void UDP_Prev() {
        if (PlayerManager.getInstance().getCurrentPlaying().isFirst() && !PlayerManager.getInstance().isLoop()) {
            return;
        }
        if (timer!=null) {
            timer.cancel();
            isTimerRunning = false;
        }
        PlayerManager.getInstance().playPrev();
        Log.d(PlayerManager.TAG, "上一个：" + PlayerManager.getInstance().getCurrentPlaying().getName());
        startPlay();
    }
    @Override
    public void UDP_Next() {
        if (PlayerManager.getInstance().getCurrentPlaying().isLast() && !PlayerManager.getInstance().isLoop()) {
            if (this.currentPlayingMediaType == VideoActivity.MEDIA_PLAYING_TYPE_VIDEO) {
                player.setPlayWhenReady(false);
                player.seekTo(player.getDuration());
            } else if (this.currentPlayingMediaType == VideoActivity.MEDIA_PLAYING_TYPE_IMAGE) {
                if (timer!=null) {
                    timer.cancel();
                    isTimerRunning = false;
                }
            }
        } else {
            if (timer != null) {
                timer.cancel();
                isTimerRunning = false;
            }
            PlayerManager.getInstance().playNext();
            Log.d(PlayerManager.TAG, "下一个：" + PlayerManager.getInstance().getCurrentPlaying().getName());
            startPlay();
        }
    }

    @Override
    public void processConfig(String path) {
        Log.d(PlayerManager.TAG, "主界面提示刚刚插入U盘中发现播放列表：" + path);
        Intent intent = new Intent(VideoActivity.this, FileCopyActivity.class);
        intent.putExtra("path", path);
        startActivity(intent);
        this.finish();
    }

    @Override
    public void noConfig() {
        Log.d(PlayerManager.TAG, "主界面提示，没有找到播放列表");
        Toast.makeText(getApplicationContext(), "没有找到播放列表", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void externalStorageUnmounted() {
        Log.d(PlayerManager.TAG, "主界面提示：外部存储已经拔出");
    }
}
